package com.xiaoq.manager.repository.impl;

import java.util.List;

import org.mongodb.morphia.Datastore;
import org.mongodb.morphia.query.FindOptions;
import org.mongodb.morphia.query.Query;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.xiaoq.coms.util.IdGeneratorUtils;
import com.xiaoq.manager.entity.MerchantRoleEntity;
import com.xiaoq.manager.repository.IMerchantRoleRepository;

@Repository
public class MerchantRoleRepositoryImpl implements IMerchantRoleRepository {
	
	@Autowired
	private Datastore datastore;
	
	private static final Logger LOG = LoggerFactory.getLogger(MerchantRoleRepositoryImpl.class);

	@Override
	public MerchantRoleEntity findMerchantRole(String code) {
		
		return datastore.find(MerchantRoleEntity.class).field("code").equal(code).get();
	}

	@Override
	public List<MerchantRoleEntity> findMerchantRole() {
		
		return datastore.find(MerchantRoleEntity.class).asList();
	}

	@Override
	public List<MerchantRoleEntity> findMerchantRoleBySitesId(String sitesId) {
		return datastore.find(MerchantRoleEntity.class).field("sitesId").equal(sitesId).asList();
	}

	@Override
	public MerchantRoleEntity add(MerchantRoleEntity merchantRole) {
		datastore.save(merchantRole);
		return merchantRole;
	}

	@Override
	public MerchantRoleEntity findById(String id) {
		MerchantRoleEntity merchantRole = datastore.find(MerchantRoleEntity.class).field(IdGeneratorUtils.IDGENERATOR).equal(id).get();
		return merchantRole;
	}

	@Override
	public boolean deleteMerchantRole(String roleId) {
		Query<MerchantRoleEntity> merchantRoleQuery = datastore.find(MerchantRoleEntity.class).field(IdGeneratorUtils.IDGENERATOR).equal(roleId);
		datastore.delete(merchantRoleQuery);
		return true;
	}

	@Override
	public boolean findMerchantRoleByRoleName(String roleName,String shopId) {
		Query<MerchantRoleEntity> merchantRoleQuery = datastore.find(MerchantRoleEntity.class);
		merchantRoleQuery.field("name").equal(roleName);
		merchantRoleQuery.field("sitesId").equal(shopId);
		if(merchantRoleQuery!=null&&merchantRoleQuery.count()!=0){
			return true;
		}
		return false;
	}

}
